package com.cens.mall.commodity.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.cens.common.constant.CommodityConstant;
import com.cens.common.to.SkuReductionTo;
import com.cens.common.to.SpuBoundsTo;
import com.cens.common.to.es.SkuESModel;
import com.cens.common.utils.R;
import com.cens.mall.commodity.dao.SpuInfoDescDao;
import com.cens.mall.commodity.entity.*;
import com.cens.mall.commodity.feign.CouponFeignService;
import com.cens.mall.commodity.feign.SearchFeignService;
import com.cens.mall.commodity.feign.WareFeignService;
import com.cens.mall.commodity.service.*;
import com.cens.mall.commodity.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cens.common.utils.PageUtils;
import com.cens.common.utils.Query;

import com.cens.mall.commodity.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //1.保存SPU基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        //2.保存SPU的描述、图片
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        //3.保存SPU的图片集
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        //4.保存SPU的规格参数
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream()
                .map(
                        attr -> {
                            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                            productAttrValueEntity.setAttrId(attr.getAttrId());
                            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
                            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
                            productAttrValueEntity.setAttrValue(attr.getAttrValues());
                            productAttrValueEntity.setQuickShow(attr.getShowDesc());
                            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
                            return productAttrValueEntity;
                        }
                ).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(productAttrValueEntities);

        //5.保存SPU的积分信息
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if (r.getCode() != 0) {
            log.error("保存spu积分信息失败 result:" + r);
        }
        //6.保存当前SPU对应的所有SKU信息
        List<Skus> skus = spuSaveVo.getSkus();
        if (CollectionUtils.isNotEmpty(skus)) {

            for (Skus sku : skus) {
                //6.1.保存SKU基本信息
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(
                        sku.getImages().stream()
                                .filter(skuImg -> skuImg.getDefaultImg() == 1)
                                .findFirst()
                                .map(Images::getImgUrl)
                                .orElse(null)
                );
                skuInfoService.saveSkuInfo(skuInfoEntity);
                //6.2.保存SKU的图片信息
                List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream()
                        .filter(skuImg -> StringUtils.isNotEmpty(skuImg.getImgUrl()))
                        .map(
                                skuImg -> {
                                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                                    skuImagesEntity.setImgUrl(skuImg.getImgUrl());
                                    skuImagesEntity.setDefaultImg(skuImg.getDefaultImg());
                                    return skuImagesEntity;
                                }
                        ).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(skuImagesEntities)) {
                    skuImagesService.saveBatch(skuImagesEntities);
                }
                //6.3.保存SKU销售属性信息
                List<Attr> skuAttrs = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = skuAttrs.stream()
                        .map(
                                skuAttr -> {
                                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                                    BeanUtils.copyProperties(skuAttr, skuSaleAttrValueEntity);
                                    return skuSaleAttrValueEntity;
                                }
                        ).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                //6.4.保存SKU的优惠信息
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) > 0) {
                    R skuReductionResult = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (skuReductionResult.getCode() != 0) {
                        log.error("保存sku优惠信息失败 result:" + r);
                    }
                }
            }

        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> spuInfoEntityQueryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            spuInfoEntityQueryWrapper.and(
                    w -> w.eq("id", key).or().like("spu_name", key)
            );
        }
        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(status)) {
            spuInfoEntityQueryWrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            spuInfoEntityQueryWrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            spuInfoEntityQueryWrapper.eq("catelog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                spuInfoEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {

        //查询sku信息
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuInfo(spuId);

        //查询sku属性
        List<ProductAttrValueEntity> baseAttr = productAttrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = baseAttr.stream()
                .map(ProductAttrValueEntity::getAttrId)
                .collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);
        HashSet<Long> idSet = new HashSet<>(searchAttrIds);

        List<SkuESModel.Attrs> attrs = baseAttr.stream()
                .filter(item -> idSet.contains(item.getAttrId()))
                .map(
                        item -> {
                            SkuESModel.Attrs attr = new SkuESModel.Attrs();
                            BeanUtils.copyProperties(item, attr);
                            return attr;
                        }
                )
                .collect(Collectors.toList());
        //查询sku是否有库存
        Map<Long, Boolean> hasStockMap = null;
        try {
            R result = wareFeignService.getSkusHasStock(skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList()));
            hasStockMap = result.getData(new TypeReference<List<SkuHasStockVo>>(){}).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId,SkuHasStockVo::getHasStock));
        }catch (Exception e){
            log.error("查询库存失败",e);
        }
        //封装
        Map<Long, Boolean> finalHasStockMap = hasStockMap;
        List<SkuESModel> skuESModels = skus.stream()
                .map(
                        sku -> {
                            SkuESModel skuESModel = new SkuESModel();
                            BeanUtils.copyProperties(sku, skuESModel);
                            skuESModel.setSkuPrice(sku.getPrice());
                            skuESModel.setSkuImg(sku.getSkuDefaultImg());
                            //查询商品是否有库存
                            if (finalHasStockMap == null) {
                                skuESModel.setHasStock(true);
                            } else {
                                skuESModel.setHasStock(finalHasStockMap.get(sku.getSkuId()));
                            }
                            //设置商品热度评分，先默认我0
                            skuESModel.setHotScore(0L);
                            //查询品牌及分类信息
                            BrandEntity brandEntity = brandService.getById(skuESModel.getBrandId());
                            skuESModel.setBrandImg(brandEntity.getLogo());
                            skuESModel.setBrandName(brandEntity.getName());
                            CategoryEntity categoryEntity = categoryService.getById(skuESModel.getCatalogId());
                            skuESModel.setCatalogName(categoryEntity.getName());

                            //设置检索属性
                            skuESModel.setAttrs(attrs);
                            return skuESModel;
                        }
                ).collect(Collectors.toList());
        R r = searchFeignService.commodityStatusUp(skuESModels);
        if(r.getCode() == 0){
            //修改spu状态
            this.baseMapper.updateSpuStatus(spuId, CommodityConstant.SpuStatusEnum.SPU_UP.getCode());
        }else{
            //重复调用？接口幂等性？
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long id) {
        SkuInfoEntity skuinfo = skuInfoService.getById(id);
        return getById(skuinfo.getSpuId());
    }

}